<template>
  <div>
    <h1>简易的表格</h1>
    <Common-tabel :data="goodslist">
      <!--标题插槽  -->
      <template v-slot:header>
        <th>序号</th>
        <th>商品名称</th>
        <th>价格</th>
        <th>标签</th>
        <th>操作</th>
      </template>
      <!--主体内容插槽  -->
      <template v-slot:body="{ row, index }">
        <td>{{ index + 1 }}</td>
        <td>{{ row.goods_name }}</td>
        <td>{{ row.goods_price }}</td>
        <td>
          <input type="text" class="form-control form-control-sm form-input" v-if="row.inputVisible" v-focus
            v-model.trim="row.inputValue" @blur="propValue(row)" />
          <button class="btn btn-primary btn-sm" type="button" v-else @click="row.inputVisible = true">
            +Tags
          </button>
          <span class="badge badge-warning ml-2" v-for="x in row.tags" :key="x">{{ x }}</span>
        </td>
        <td>
          <button class="btn btn-danger btn-sm" type="button" @click="remove(row.id)">
            删除
          </button>
        </td>
      </template>
    </Common-tabel>
  </div>
</template>

<script>
import CommonTabel from "./components/common-tabel/index.vue";
export default {
  name: "App",
  components: { CommonTabel },
  data() {
    return {
      goodslist: [],
    };
  },
  methods: {
    // 初始化商品信息
    async getgoodlist() {
      // 发送ajax
      const { data: res } = await this.$axios.get("/api/goods");
      if (res.status !== 0) return alert("获取商品信息失败,请检查网络!");
      const list = res.data;
      console.log(list);
      return (this.goodslist = list);
    },
    // 删除商品
    remove(id) {
      // 通过商品id进行过滤，如果当前的id不等于商品的id那么就进行删除操作
      this.goodslist = this.goodslist.filter((x) => x.id !== id);
    },
    // 显示文本框
    // 传递数值
    propValue(row) {
      // 存值
      const val = row.inputValue;
      console.log(val);
      // 清空
      row.inputValue = "";
      // 隐藏
      row.inputVisible = false;
      // 添加新标签
      /* 1.判断是否为空
      2.判断当前值是否存在或者是否重复 */
      if (!val || row.tags.indexOf(val) !== -1) return
      // 将文本框的值添加到数组中
      row.tags.push(val);
    }
  },
  created() {
    this.getgoodlist();
  },
  // 创建v-focus自定义指令
  directives: {
    // 自动获取焦点
    focus(el) {
      el.focus();
    },
  },
};
</script>
<style lang="less" scoped>
.form-input {
  width: 80px;
  display: inline-block;
  margin-right: 5px;
}
</style>